#!/bin/bash

CUR_DIR=$(realpath $0|xargs -I abspath dirname "abspath")

ARCH=arm
#ARCH=arm64
export ANDROID_API="android-21"
if [ ! -z ${NDK_ROOT} ]; then
    ANDROID_NDK_ROOT=${NDK_ROOT}
else
    echo "Please set the NDK_ROOT in environment....."
    exit
fi

if [ "$(uname)" == "Darwin" ]; then
export PATH=${ANDROID_NDK_ROOT}/toolchains/llvm/prebuilt/darwin-x86_64/bin:${PATH}
elif [ "$(expr substr $(uname -s) 1 5)"=="Linux" ];then
export PATH=${ANDROID_NDK_ROOT}/toolchains/llvm/prebuilt/linux-x86_64/bin:${PATH}
#elif [ "$(expr substr $(uname -s) 1 10)"=="MINGW32_NT" ];then
fi

case ${ARCH} in
    arm)
        OS_PLATFORM=android-arm
        BUILD_FLAGS=-march=armv7-a -mthumb -Wl,--fix-cortex-a8 -mfloat-abi=softfp -mfpu=vfpv3-d16
        HOST=arm-linux-androideabi
        export CC=armv7a-linux-androideabi21-clang
        export CXX=armv7a-linux-androideabi21-clang++
    ;;
    arm64)
        OS_PLATFORM=android64-aarch64
        BUILD_FLAGS=-target aarch64-linux-android
        HOST=aarch64-linux-android
        export CC=aarch64-linux-android21-clang
        export CXX=aarch64-linux-android21-clang++
    ;;
    x86)
        OS_PLATFORM=android-x86
        BUILD_FLAGS=-march=i686 -mtune=intel -mssse3 -mfpmath=sse -m32
    ;;
    x86_64)
        OS_PLATFORM=android64-x86_64
        BUILD_FLAGS=-march=x86-64 -msse4.2 -mpopcnt -m64 -mtune=intel
    ;;
esac

export ANDROID_SYSROOT="$ANDROID_NDK_ROOT/platforms/$ANDROID_API/arch-${ARCH}"
export CROSS_SYSROOT=${ANDROID_SYSROOT}
export SYSROOT=${ANDROID_SYSROOT}
export HOSTCC=gcc


echo "***************************************************************************"
echo "Build......."
echo "***************************************************************************"
cd ${CUR_DIR}
OUT_DIR=${CUR_DIR}/out/${OS_PLATFORM}
if [ -d ${OUT_DIR} ]; then
    rm -rf ${OUT_DIR}
fi
mkdir -p ${OUT_DIR}

./autogen.sh
./configure \
        --with-sysroot=${SYSROOT} \
        --enable-static \
        --enable-shared \
        --host=${HOST} \
        ${BUILD_FLAGS} \
        --prefix=${OUT_DIR}

make -j8

make install

